<template>
  <div class="user_box">
    <div class="user_container">
      <h2>用户登录</h2>
      <!-- 注册对话框 -->
      <el-form
        :model="loginForm"
        :rules="loginFormRules"
        ref="loginFormRef"
        label-width="0px"
        class="user_form"
      >
        <el-form-item
          label=""
          prop="email"
        >
          <el-input
            v-model="loginForm.email"
            prefix-icon="el-icon-message"
            placeholder="请输入邮箱"
          ></el-input>
        </el-form-item>
        <el-form-item
          label=""
          prop="psw"
        >
          <el-input
            type="password"
            v-model="loginForm.psw"
            autocomplete="off"
            prefix-icon="el-icon-lock"
            placeholder="请输入密码"
          ></el-input>
        </el-form-item>
        <el-form-item class="user_item">
          <el-button type="primary" class="user_btn" @click="handleLogin">登录</el-button>
        </el-form-item>
        <el-form-item class="go_user goReg">
          <a href="javascript:;" @click="go_reg">快速注册</a>
          <a href="javascript:;">忘记密码?</a>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
import '../assets/css/user.css'

export default {
  data () {
    const validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'))
      } else {
        if (this.loginForm.checkPass !== '') {
          this.$refs.loginFormRef.validateField('checkPass')
        }
        callback()
      }
    }
    return {
      // 注册表单对象
      loginForm: {
        email: '',
        psw: ''
      },
      // 注册表单校验规则
      loginFormRules: {
        email: [
          { required: true, message: '请输入邮箱地址', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
        ],
        psw: [
          { validator: validatePass, trigger: 'blur' }
        ]
      }

    }
  },
  created () {},
  methods: {
    // 点击按钮注册
    handleLogin () {
      // 表单预校验
      this.$refs.loginFormRef.validate(async valid => {
        if (!valid) return
        // 成功 发起请求
        const { data: res } = await this.$http.post('http://127.0.0.1:3000/login', this.loginForm)
        console.log(res)
        if (res.err_code !== 0) {
          return this.$message.error({
            duration: 800,
            message: '用户名或密码错误！'
          })
        }
        // 存储 token
        window.sessionStorage.setItem('token', JSON.stringify(res.token))
        window.sessionStorage.setItem('loginId', JSON.stringify(res.id))

        this.$message.success({
          duration: 800,
          message: '登录成功！'
        })
        this.$router.push('/')
      })
    },
    // 快速注册
    go_reg () {
      this.$router.push('/register')
    }
  }
}
</script>

<style lang="less" scoped>
</style>
